# -*- coding:utf-8 -*-

"""
    客户端请求检查是否有更新zip包
"""


import tornado.web
from utils.routes import route
from utils import log as logger
from utils import mongo
from configure import config



@route('/update/check?', 'update.check')
class CheckZipHandler(tornado.web.RequestHandler):
    """ 客户端请求检查是否有更新zip包
    """
    db_name = config.DB_NAME
    collection_name = config.COLLECTION_DATAS

    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self, *argl, **argd):
        scope = self.get_argument('scope', None)
        sn_id = self.get_argument('sn_id', None)
        ver = self.get_argument('ver', None)

        logger.info('scope:', scope, 'sn_id:', sn_id, 'ver:', ver, caller=self)

        if not sn_id or not ver or len(sn_id) != 15 or scope not in ['test', 'online']:
            self.finish({'code': 1, 'info': 'parmas error!'})
            return

        results = {'code':      0,
                   'result':    {
                                 'sn_id':           sn_id,
                                 'ver_from':        ver,
                                 'availbe_update':  0,
                                 'update_url':      '',
                                 'md5':             '',
                                 'ts':              '',
                                 'info':            '',
                                 'size':             0,
                                 'scope':           scope
                              }}
        sn_id_6 = sn_id[:6]   # 取前6位

        spec = {
            'sn_ids':       {'$in': [sn_id_6]}, # 校验sn_id
            'ver_from':     ver,                # 版本号需要对应
            # 'ver':          {'$gte': ver},      # 升级包的版本必须大于现有版本
            'scope':        scope,              # 更新包的域，测试或正式，默认查询正式域
            'status':       '1'                 # 更新包是否已激活，只能更新已激活的包
        }

        # 如果是白名单里的sn_id号，那么就不限制域
        from service import sn_id as global_test_sn_ids
        if sn_id in global_test_sn_ids.TOTAL_TEST_SN_IDS:
            del spec['scope']
        else:
            spec['device_scope'] = '0'          # 设备范围不限，不能更新白名单里的设备范围
        logger.info('global_test_sn_ids =', global_test_sn_ids.TOTAL_TEST_SN_IDS, 'sn_id =', sn_id, caller=self)

        r = yield tornado.gen.Task(mongo.find_all, self.db_name, self.collection_name, spec)
        if r:
            r.sort(lambda x,y:compareversion(x['ver'],y['ver']))
            d = r[-1]   # 只取最新的更新包

            update_flag = True
            if compareversion(d['ver'],ver) <= 0:
                update_flag = False
                logger.info("no new version")

            if update_flag:
                results['result']['availbe_update'] = 1
                results['result']['ver']            = d['ver']
                results['result']['update_url']     = d['download_url']
                results['result']['md5']            = d['md5']
                results['result']['ts']             = d['ts'] * 1000    # 客户端需要毫秒
                results['result']['info']           = d['info']
                results['result']['size']           = d['size']
                results['result']['finger_point']   = d['finger_point']
                results['result']['create_time']    = d['create_time']
        self.finish(results)
        logger.info('do response:', results, caller=self)

    def post(self, *argl, **argd):
        self.get(*argl, **argd)
        
def compareversion(version1, version2):
    i = 0
    result = 0

    version1_strs = version1.split(".")
    version2_strs = version2.split(".")

    while (i < 4 and not result):
        pos_result =  cmp(int(version1_strs[i]), int(version2_strs[i]))
        if pos_result:
            result = pos_result
        else:
            i += 1

    return result

# if __name__ == '__main__':
#     r = [{'ver':"0.7.1.10"}, {'ver':"0.7.1.0"}]
#     r.sort(lambda x,y:compareversion(x['ver'],y['ver']))
#     print r